package com.levi.pay.controller;

import com.levi.pojo.PayInfo;
import com.levi.pay.service.PayService;
import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shentong
 * @since 2022/3/16 10:12 PM
 */
@Slf4j
@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private PayService payService;
    @Autowired
    private WxPayConfig wxPayConfig;

    @GetMapping("/create")
    public ModelAndView create(@RequestParam String orderId,
                               @RequestParam BigDecimal amount,
                               @RequestParam BestPayTypeEnum payType
                               ) {
        PayResponse payResponse = payService.create(orderId, amount,payType);
        Map<String, Object> map = new HashMap<>();
        if (payType == BestPayTypeEnum.WXPAY_NATIVE) {
            map.put("codeUrl", payResponse.getCodeUrl());
            map.put("orderId", orderId);
            map.put("returnUrl", wxPayConfig.getReturnUrl());
            return new ModelAndView("createForWxNavite",map);
        } else if (payType == BestPayTypeEnum.ALIPAY_PC) {
            map.put("body", payResponse.getBody());
            return new ModelAndView("createForAliPC", map);
        }
        throw new RuntimeException("不支持的支付方式");
    }

    @PostMapping("/asyncNotify")
    @ResponseBody
    public String asyncNotify(@RequestBody String notifyData) {
        return payService.asyncNotify(notifyData);
    }

    @GetMapping("/toSuccess")
    public ModelAndView Tosuccess() {
        return new ModelAndView("success");
    }

    @GetMapping("/getPayInfoByOrderId")
    @ResponseBody
    public PayInfo getPayInfoByOrderId(@RequestParam String orderId) {
        return payService.getPayInfoByOrderId(orderId);
    }
}
